// pages/sniff/sniff.ts
const util = require('../../utils/util')
const common = require('../../utils/common')

Page({
  data: {
    UploadSpeed: "N/A",
    DownloadSpeed: "N/A",
    IsTesting: false
  },

  onShow() {
    console.log("Enable Test")
    this.setData({
      IsTesting: true
    })
    this.StartTest()
  },
  onHide() {
    console.log("Disable Test")
    this.setData({
      IsTesting: false
    })
  },

  // 开始测试函数，使用异步来测试
  // 调试函数时保存完，需终止后重启以使IsTesting处于正常的值 o(TヘTo)
  StartTest() {
    async function SpeedTestWhile(_this: any) {
      // do something
      // 一次下载，一次上传
      console.log("SpeedTestWhile Start")
      while (_this.data.IsTesting) {
        console.log("SpeedTestWhile TestOnce IsTesting",_this.data.IsTesting)
        // downland test
        let start = new Date().getTime()
        let data = await common.requestSync("https://5gtest.shangdu.com:8080/download?size=2500000&r=0.8661664090652565d", "GET", null, null)
        let end = new Date().getTime()
        let time = end - start
        _this.setData({
          DownloadSpeed: (20000 / time).toFixed(3).slice(0, -1).toString() + "Mbps"
        })

        // upload test
        start = new Date().getTime()
        await common.requestSync("https://node-124-47-2-51.speedtest.cn:51090/upload?r=0.047851478077041154", "POST", data, null);
        end = new Date().getTime()
        time = end - start;
        _this.setData({
          UploadSpeed: (20000 / time).toFixed(3).slice(0, -1).toString() + "Mbps"
        })
        // await util.Sleep(1000)
      }
      console.log("SpeedTestWhile Exit")
    }
    SpeedTestWhile(this)
  }
})